package learn_fream

import (
	"context"
	"go_fream/api/learn_fream"
	"go_fream/internal/dao"
	"go_fream/internal/model/do"
	"go_fream/internal/model/entity"
	"go_fream/internal/service"

	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/gogf/gf/v2/os/gtime"
)

type Learn struct {
}

func NewLearn() *Learn {
	return &Learn{}
}

func (c *Learn) GetEmpNew(ctx context.Context, req *learn_fream.LearnReq) (res *learn_fream.LearnRes, err error) {
	md := dao.Emp.Ctx(ctx)
	var emps []entity.Emp

	err = md.Scan(&emps)

	if err != nil {
		return nil, err
	}
	return
}

func (c *Learn) LearnLogicBook(req *ghttp.Request) {
	books, err := service.Book().GetList(req.Context())
	if err != nil {
		req.Response.Writeln("发生错误： " + err.Error())
	}
	req.Response.WriteJson(books)
}

func (c *Learn) GetDeptCustem(req *ghttp.Request) {

	type MyDept struct {
		g.Meta `orm:"table:dept"`
		Id     uint   `json:"id"`   // ID
		Name   string `json:"name"` //部门名称
	}

	type MyEmp struct {
		g.Meta `orm:"table:emp"`
		Id     uint   `json:"id"`      // ID
		DeptId string `json:"dept_id"` //所属部门
		Name   string `json:"name"`    // 姓名
		Phone  string `json:"phone"`   // 联系电话

		Dept *MyDept `json:"dept" orm:"with:id=dept_id"`
	}

	md := dao.Emp.Ctx(req.Context())

	var emps []MyEmp

	err := md.With(MyDept{}).Scan(&emps)

	if err != nil {
		req.Response.Writeln("发生错误： " + err.Error())
	}
	req.Response.WriteJson(emps)
}

func (c *Learn) GetDept(req *ghttp.Request) {

	md := dao.Dept.Ctx(req.Context())

	var depts []entity.Dept

	err := md.With(entity.Emp{}, entity.Hobby{}).Scan(&depts)

	if err != nil {
		req.Response.Writeln("发生错误： " + err.Error())
	}
	req.Response.WriteJson(depts)
}

func (c *Learn) GetEmp(req *ghttp.Request) {

	md := dao.Emp.Ctx(req.Context())

	//var emps []entity.Emp
	//err := md.Scan(&emps)
	var emps []*entity.Emp
	//关联一张表
	//err := md.With(entity.Dept{}).Scan(&emps)
	// 关联多张表
	err := md.With(entity.Dept{}, entity.Hobby{}).Scan(&emps)

	if err != nil {
		req.Response.Writeln("发生错误： " + err.Error())
	}
	req.Response.WriteJson(emps)
}

func (c *Learn) DbDao(req *ghttp.Request) {

	//空值处理
	md := dao.Book.Ctx(req.Context())
	book := do.Book{ // 0 "" nil
		Price: 55.55,
	}
	result, err := md.Where(do.Book{Id: 8}).Data(book).Update()
	if err != nil {
		req.Response.Writeln("发生错误：" + err.Error())
	}
	req.Response.WriteJson(result)

	// 更新
	//md := dao.Book.Ctx(req.Context())
	//book := entity.Book{
	//	Author: "王强",
	//	Price:  88.88,
	//}
	//result, err := md.Fields("author", "price").Where("id", 8).Data(book).Update()
	//if err != nil {
	//	req.Response.Writeln("发生错误：" + err.Error())
	//}
	//req.Response.WriteJson(result)

	// 查询
	//md := dao.Book.Ctx(req.Context())
	//md = md.WhereGT("id", 2)
	//md = md.WhereLT("id", 5)
	//books, err := md.All()
	//if err != nil {
	//	req.Response.Writeln("发生错误：" + err.Error())
	//}
	//req.Response.WriteJson(books)
}

func (c *Learn) QuerySql(req *ghttp.Request) {
	db := g.DB()
	//新增数据
	sql := "INSERT INTO `book` (`name`, `author`, `price`) VALUES (?, ?, ?)"
	data := g.Array{"Go语言从入门到精通", "Go语言研讨组", 99.98}
	books, err := db.Exec(req.Context(), sql, data)
	// 查询
	//books, err := db.Query(req.Context(), "SELECT * FROM `book` WHERE `id` > ? AND `id` < ?", g.Array{3, 7})
	if err != nil {
		req.Response.Writeln("发生错误：" + err.Error())
	}
	req.Response.WriteJson(books)
}

// func (c *Hello) InsertData(ctx context.Context, req *hello.DbReq) (res *hello.ParamsRes, err error)
func (c *Learn) InsertData(req *ghttp.Request) {

	type Book struct {
		ID       uint `json:"id"`
		Name     string
		BookName string `orm:"name"`
		Author   string
		Price    float64
		//PublishTime *gtime.Time
	}
	data := g.Map{
		"name":         "MYSQL从入门到跑路",
		"author":       "廖雪峰",
		"price":        69,
		"publish_time": gtime.New("2024-10-13"),
	}

	// 处理事务
	g.DB().Transaction(context.TODO(), func(ctx context.Context, tx gdb.TX) error {
		md := tx.Model("book")
		result, err := md.Insert(data)
		if err != nil {
			req.Response.Writeln("发生错误：" + err.Error())
		}
		req.Response.WriteJson(result)
		return err
	})

	//tx, err := g.DB().Begin(req.Context())
	//if err != nil {
	//	req.Response.Writeln("发生错误：" + err.Error())
	//}
	//md := tx.Model("book")
	//result, err := md.Insert(data)
	//if err == nil {
	//	tx.Commit()
	//	req.Response.WriteJson(result)
	//} else {
	//	tx.Rollback()
	//	req.Response.Writeln("发生错误：" + err.Error())
	//}

	/*
		方法	主键在数据库中已存在时
		Insert	报错，主键冲突
		Repalce	用提供的数据替换已存在同主键的数据
		Save	用提供的数据更新已存在的同主键数据
	*/
	//md := g.Model("book")
	//result, err := md.Data(data).Insert()
	//result, err := md.Insert(data)
	//result, err := md.Replace(data)
	//result, err := md.Save(data)
	//if err != nil {
	//	req.Response.Writeln("发生错误：" + err.Error())
	//}
	//req.Response.WriteJson(result)
}
